var zt;
var noc_id = 0;
var now_call_uid = 0;
var now_user_status = 0;
$.cookie('header', 'header-fixed', {
    expires: 1
});
$(function() {

    $('#sidebar .menu-scroll').css('overflow', 'initial');
    if ($('body').hasClass('sidebar-collapsed')) {
        $('#side-menu').attr('style', '').parent('.slimScrollDiv').replaceWith($('#side-menu'));
    } else {
        setTimeout(function() {
            $('#side-menu').slimScroll({
                "height": $(window).height() - 50,
                'width': '250px',
                "wheelStep": 5
            });
            $('#side-menu').focus();
        }, 50)
    }


    //BEGIN MENU SIDEBAR
    $('#sidebar').css('min-height', '100%');
    $('#side-menu').metisMenu();
    $(window).on("load resize", function() {
        if ($(this).width() < 768) {
            $('body').removeClass();
            $('div.sidebar-collapse').addClass('collapse');
        } else {
            $('body').addClass($.cookie('menu_style') + ' ' + $.cookie('header'));
            $('div.sidebar-collapse').removeClass('collapse');
            $('div.sidebar-collapse').css('height', 'auto');
        }

        if ($('#sidebar').height() > $('#page-wrapper').height()) {

            //$('#wrapper').css('height', $('#sidebar').height());
        }
    });

    $('#news-ticker-close').click(function(e) {
        $('.news-ticker').remove();
        $('.quick-sidebar').css('top', '50px');
    });
    //END NEWS TICKER TOPBAR

    //BEGIN TOPBAR DROPDOWN
    $('.dropdown-slimscroll').slimScroll({
        "height": '250px',
        "wheelStep": 30
    });
    //END TOPBAR DROPDOWN

    //BEGIN CHECKBOX & RADIO
    if ($('#demo-checkbox-radio').length <= 0) {
        $('input[type="checkbox"]:not(".switch")').iCheck({
            checkboxClass: 'icheckbox_minimal-grey',
            increaseArea: '20%' // optional
        });
        $('input[type="radio"]:not(".switch")').iCheck({
            radioClass: 'iradio_minimal-grey',
            increaseArea: '20%' // optional
        });
    }
    //END CHECKBOX & RADIO

    //BEGIN TOOTLIP
    $("[data-toggle='tooltip'], [data-hover='tooltip']").tooltip();
    //END TOOLTIP

    //BEGIN POPOVER
    $("[data-toggle='popover'], [data-hover='popover']").popover();
    //END POPOVER

    //BEGIN THEME SETTING
    $('#theme-setting > a.btn-theme-setting').click(function() {
        if ($('#theme-setting').css('right') < '0') {
            $('#theme-setting').css('right', '0');
        } else {
            $('#theme-setting').css('right', '-250px');
        }
    });

    // Begin Change Theme Color
    var list_menu = $('.dropdown-theme-setting > li > select#list-menu');
    var list_style = $('.dropdown-theme-setting > li > select#list-style');
    var list_header = $('.dropdown-theme-setting > li > select#list-header');
    var list_color = $('.dropdown-theme-setting > li > ul#list-color > li');
    /*$('#list-color').hasClass(function(){              
                ($(this).hasClass('edit-Phone')){
                   $.get('{:U("Common/color")}'+'&t=' + Math.random(1000),'&color={$color}', function(data){
                    parent.layer.open({
                      type: 1,
                      area: ['600px', '330px'],
                      title: '编辑号码',
                      shadeClose:true,
                      content: data
                    });
                  })*/
    // FUNCTION CHANGE URL STYLE ON HEAD TAG
    var setTheme = function(menu_style, style, header, color) {
        $.cookie('menu_style', menu_style);
        $.cookie('style', style);
        $.cookie('header', header);
        $.cookie('color', color);
        /*var x = getElementById('theme-setting');
        var y = getElementByTagName('li');
        var c = y.getClassName;*/
        $('body').removeClass();
        $('body').addClass(menu_style + ' ' + header);
        // Set slimscroll when sidebar fixed
        //alert(111); 
        $('#theme-change').attr('href', _public_path + '/css/themes/' + style + '/' + color + '.css');
        //alert(_public_path+'/css/themes/'+ style + '/' + color + '.css');
    }


    // INITIALIZE THEME FROM COOKIE
    // --NOTES: HAVE TO SET VALUE FOR STYLE & COLOR BEFORE AND AFTER ACTIVE THEME
    // Check cookie when window reload and set value for each option(menu,style,color)
    //setTheme($.cookie('menu_style'), $.cookie('style'),'header-fixed', $.cookie('color'));
    if ($.cookie('style')) {
        //alert(111);
        // FIX SIDEBAR IN HORIZONTAL AND RIGHT
        if ($('body').hasClass('clear-cookie')) {
            $.removeCookie('menu_style');

        } else {

            list_menu.find('option').each(function() {
                if ($(this).attr('value') == $.cookie('menu_style')) {
                    $(this).attr('selected', 'selected');
                }
            });

            list_style.find('option').each(function() {
                if ($(this).attr('value') == $.cookie('style')) {
                    $(this).attr('selected', 'selected');
                }
            });

            /*  list_header.find('option').each(function(){
                  if($(this).attr('value') == $.cookie('header')) {
                      $(this).attr('selected', 'selected');
                  }
              });*/

            list_color.removeClass("active");
            list_color.each(function() {

                if ($(this).attr('data-color') == $.cookie('color')) {
                    $(this).addClass('active');
                }
            });


            //setTheme($.cookie('menu_style'), $.cookie('style'),'header-fixed', $.cookie('color'));
        }

    };

    // SELECT MENU STYLE EVENT
    list_menu.on('change', function() {
        list_color.each(function() {
            if ($(this).hasClass('active')) {
                color_active = $(this).attr('data-color');
            }
        });
        // No Menu style 3 fixed
        if (($.cookie('header') == 'header-fixed') && ($(this).val() == 'sidebar-icons')) {
            setTheme($(this).val(), list_style.val(), 'header-fixed', color_active);
            return;
        }
        setTheme($(this).val(), list_style.val(), 'header-fixed', color_active);
    });
    // SELECT STYLE EVENT
    list_style.on('change', function() {
        list_color.each(function() {
            if ($(this).hasClass('active')) {
                color_active = $(this).attr('data-color');
            }
        });
        setTheme(list_menu.val(), $(this).val(), 'header-fixed', color_active);
    });

    // SELECT HEADER EVENT
    list_header.on('change', function() {
        list_color.each(function() {
            if ($(this).hasClass('active')) {
                color_active = $(this).attr('data-color');
            }
        });
        // No Menu style 3 fixed
        if (($.cookie('menu_style') == 'sidebar-icons') && ($(this).val() == 'header-fixed')) {
            return;
        }
        setTheme(list_menu.val(), list_style.val(), 'header-fixed', color_active);
    });
    // LI CLICK EVENT
    list_color.on('click', function() {
        list_color.removeClass('active');
        $(this).addClass('active');
        //alert(list_menu.val());
        setTheme(list_menu.val(), list_style.val(), 'header-fixed', $(this).attr('data-color'));
        //传data-color到userAction
        var url = 'index.php?m=user&a=userColor&t=' + Math.random(1000) + '&color=' + $(this).attr('data-color');
        //console.log(url);
        $.get(url, function(data) {});
    });
    $('.btn-fullscreen').click(function() {

        if (!document.fullscreenElement && // alternative standard method
            !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement) { // current working methods
            if (document.documentElement.requestFullscreen) {
                document.documentElement.requestFullscreen();
            } else if (document.documentElement.msRequestFullscreen) {
                document.documentElement.msRequestFullscreen();
            } else if (document.documentElement.mozRequestFullScreen) {
                document.documentElement.mozRequestFullScreen();
            } else if (document.documentElement.webkitRequestFullscreen) {
                document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
            }
        } else {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.msExitFullscreen) {
                document.msExitFullscreen();
            } else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            }
        }
    });
    //END FULL SCREEN

    // BEGIN FORM CHAT
    $('.btn-chat').click(function() {
        if ($('#chat-box').is(':visible')) {
            $('#chat-form').toggle('slide', {
                direction: 'right'
            }, 500);
            $('#chat-form').slimScroll();
            $('#chat-box').hide();
        } else {
            $('#chat-form').toggle('slide', {
                direction: 'right'
            }, 500);
            $('#chat-form > .chat-inner').slimScroll({
                "height": $(window).height(),
                'width': '280px',
                "wheelStep": 30
            });
        }
    });
    $('.chat-box-close').click(function() {
        $('#chat-box').hide();
        $('#chat-form .chat-group a').removeClass('active');
    });
    $('.chat-form-close').click(function() {
        $('#chat-form').toggle('slide', {
            direction: 'right'
        }, 500);
        $('#chat-box').hide();
    });

    init_InfoPanel();
    //点击page-content其它区域，面板收回



    $('#chat-form .chat-group a').unbind('*').click(function() {
        $('#chat-box').hide();
        $('#chat-form .chat-group a').removeClass('active');
        $(this).addClass('active');
        var strUserName = $('> small', this).text();
        $('.display-name', '#chat-box').html(strUserName);
        var userStatus = $(this).find('span.user-status').attr('class');
        $('#chat-box > .chat-box-header > span.user-status').removeClass().addClass(userStatus);
        var chatBoxStatus = $('span.user-status', '#chat-box');
        var chatBoxStatusShow = $('#chat-box > .chat-box-header > small');
        if (chatBoxStatus.hasClass('is-online')) {
            chatBoxStatusShow.html('在线');
        } else if (chatBoxStatus.hasClass('is-offline')) {
            chatBoxStatusShow.html('离线');
        } else if (chatBoxStatus.hasClass('is-busy')) {
            chatBoxStatusShow.html('忙');
        } else if (chatBoxStatus.hasClass('is-idle')) {
            chatBoxStatusShow.html('空闲');
        }

        var offset = $(this).offset();
        var h_main = $('#chat-form').height();
        var h_title = $("#chat-box > .chat-box-header").height();
        var top = ($('#chat-box').is(':visible') ? (offset.top - h_title - 40) : (offset.top + h_title - 20));

        if ((top + $('#chat-box').height()) > h_main) {
            top = h_main - $('#chat-box').height();
        }

        $('#chat-box').css({
            'top': top
        });

        if (!$('#chat-box').is(':visible')) {
            $('#chat-box').toggle('slide', {
                direction: 'right'
            }, 500);
        }
        // FOCUS INPUT TEXT WHEN CLICK
        $("#chat-box .chat-textarea input").focus();
        $('.chat-content > .chat-box-body').slimScroll({
            "height": "250px",
            'width': '340px',
            "wheelStep": 30,
            "scrollTo": $(this).height()
        });
    });
    // Add content to form
    $('.chat-textarea input').on("keypress", function(e) {
        var $obj = $(this);
        var $me = $obj.parent().parent().find('ul.chat-box-body');
        var $my_avt = '#';
        var $your_avt = '#';
        if (e.which == 13) {
            var $content = $obj.val();

            if ($content !== "") {
                var d = new Date();
                var h = d.getHours();
                var m = d.getMinutes();
                if (m < 10) m = "0" + m;
                $obj.val(""); // CLEAR TEXT ON TEXTAREA

                var $element = "";
                $element += "<li>";
                $element += "<p>";
                $element += "<img class='avt' src='" + $my_avt + "'>";
                $element += "<span class='user'>管理员</span>";
                $element += "<span class='time'>" + h + ":" + m + "</span>";
                $element += "</p>";
                $element = $element + "<p>" + $content + "</p>";
                $element += "</li>";

                $me.append($element);
                var height = 0;
                $me.find('li').each(function(i, value) {
                    height += parseInt($(this).height());
                });

                height += '';
                $me.scrollTop(height);

                // RANDOM RESPOND CHAT
                var $res = "";
                $res += "<li class='odd'>";
                $res += "<p>";
                $res += "<img class='avt' src='" + $your_avt + "'>";
                $res += "<span class='user'>钱冬君</span>";
                $res += "<span class='time'>" + h + ":" + m + "</span>";
                $res += "</p>";
                $res = $res + "<p>" + "Ok 我知道了" + "</p>";
                $res += "</li>";
                setTimeout(function() {
                    $me.append($res);
                    $me.scrollTop(height + 100);
                }, 1000);
            }
        }
    });
    //END FORM CHAT

    //BEGIN PORTLET
    $(".portlet").each(function(index, element) {
        var me = $(this);
        $(">.portlet-header>.tools>i", me).click(function(e) {
            if ($(this).hasClass('fa-chevron-up')) {
                $(">.portlet-body", me).slideUp('fast');
                $(this).removeClass('fa-chevron-up').addClass('fa-chevron-down');
            } else if ($(this).hasClass('fa-chevron-down')) {
                $(">.portlet-body", me).slideDown('fast');
                $(this).removeClass('fa-chevron-down').addClass('fa-chevron-up');
            } else if ($(this).hasClass('fa-cog')) {
                //Show modal
            } else if ($(this).hasClass('fa-refresh')) {
                //$(">.portlet-body", me).hide();
                $(">.portlet-body", me).addClass('wait');

                setTimeout(function() {
                    //$(">.portlet-body>div", me).show();
                    $(">.portlet-body", me).removeClass('wait');
                }, 1000);
            } else if ($(this).hasClass('fa-times')) {
                me.remove();
            }
        });
    });
    //END PORTLET

    //BEGIN BACK TO TOP
    $(window).scroll(function() {
        if ($(this).scrollTop() < 200) {
            $('#totop').fadeOut();
        } else {
            $('#totop').fadeIn();
        }
    });
    $('#totop').on('click', function() {
        $('html, body').animate({
            scrollTop: 0
        }, 'fast');
        return false;
    });
    //END BACK TO TOP

    //BEGIN CHECKBOX TABLE
    $('.checkall').on('ifChecked ifUnchecked', function(event) {
        if (event.type == 'ifChecked') {
            $(this).closest('table').find('input[type=checkbox]').iCheck('check');
        } else {
            $(this).closest('table').find('input[type=checkbox]').iCheck('uncheck');
        }
    });
    //ONLY FOR USER_PROFILE PAGE
    $('.checkall-email').on('ifChecked ifUnchecked', function(event) {
        if (event.type == 'ifChecked') {
            $(this).closest('.tab-pane').find('input[type=checkbox]').iCheck('check');
        } else {
            $(this).closest('.tab-pane').find('input[type=checkbox]').iCheck('uncheck');
        }
    });
    //END CHECKBOX TABLE

    $('.option-demo').hover(function() {
        $(this).append("<div class='demo-layout animated fadeInUp'><i class='fa fa-magic mrs'></i>Demo</div>");
    }, function() {
        $('.demo-layout').remove();
    });
    $('#header-topbar-page .demo-layout').live('click', function() {
        var HtmlOption = $(this).parent().detach();
        $('#header-topbar-option-demo').html(HtmlOption).addClass('animated flash').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
            $(this).removeClass('animated flash');
        });
        $('#header-topbar-option-demo').find('.demo-layout').remove();
        return false;
    });
    $('#title-breadcrumb-page .demo-layout').live('click', function() {
        var HtmlOption = $(this).parent().html();
        $('#title-breadcrumb-option-demo').html(HtmlOption).addClass('animated flash').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
            $(this).removeClass('animated flash');
        });
        $('#title-breadcrumb-option-demo').find('.demo-layout').remove();
        return false;
    });
    // CALL FUNCTION RESPONSIVE TABS
    fakewaffle.responsiveTabs(['xs', 'sm']);

    // BEGIN SEARCH FORM ON TOPBAR
    $('#topbar-search').on('click', function(e) {
        /*  $(this).addClass('open');
          $(this).find('.form-control').focus();

          $('#topbar-search .form-control').on('blur', function (e) {
              $(this).closest('#topbar-search').removeClass('open');
             $(this).unbind('blur');
          });*/
    });
    // END SEARCH FORM ON TOPBAR

    // BEGIN DATERANGE PICKER ON BREADCRUMB
    $('.reportrange').daterangepicker({
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract('days', 1), moment().subtract('days', 1)],
                'Last 7 Days': [moment().subtract('days', 6), moment()],
                'Last 30 Days': [moment().subtract('days', 29), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')]
            },
            startDate: moment().subtract('days', 29),
            endDate: moment(),
            opens: 'left',
        },
        function(start, end) {
            $('.reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
            $('input[name="datestart"]').val(start.format("YYYY-MM-DD"));
            $('input[name="endstart"]').val(end.format("YYYY-MM-DD"));
        }
    );
    $('.reportrange span').html(moment().subtract('days', 29).format('MMMM D, YYYY') + ' - ' + moment().format('MMMM D, YYYY'));
    //END PLUGINS DATE RANGE PICKER
    keep_online();
    bindUserStatusBtn();


});
//绑定暂停继续按钮
function bindUserStatusBtn() {
    $("#btn-user-status-pause").click(function() {
        //通话中和已经暂停的状态时 是不能点击暂停的
        if (now_user_status == 4 || now_user_status == 2) {
            return false;
        } else {
            var url = 'index.php?m=User&a=userStatusChange&user_status_old=' + now_user_status + '&opt=pause';
        }
        $.getJSON(url + '&t=' + Math.random(), function(data) {});
    });
    $("#btn-user-status-unpause").click(function() {
        //只有在暂停或者事后状态时才能点击这个按钮
        if (now_user_status == 4 || now_user_status == 3) {
            var url = 'index.php?m=User&a=userStatusChange&user_status_old=' + now_user_status + '&opt=unpause';
        } else {
            return false;
        }
        $.getJSON(url + '&t=' + Math.random(), function(data) {});
    });

}

//弹屏号码数组
var phoneslist = new Array(),
    dayPhoneCount = 0;

function keep_online() {
    //console.log(111111);
    var last_time_pickup = 0,
        is_qy = 0;

    var iframe = window.frames['switch-state'];
    if (typeof(iframe) == "undefined") {
        var work_mode = 0;

    } else {

        var work_mode = 0;
        typeState = checkDesktopStatus();
        if (typeState) {
            work_mode = 1;

        } else {

            work_mode = 2;
        }
        last_time_pickup = iframe.last_time_pickup;
    }
    //判断是否在签入页面
    if (nowPageUrl.indexOf('desktop') > 0) {
        is_qy = 1;
    } else {
        is_qy = 1;
    }
    jQuery.ajax({
        type: 'GET',
        url: 'index.php?m=User&a=keepOnline',
        dataType: "json",
        data: {
            'is_qy': is_qy,
            'work_mode': work_mode,
            't': Math.random()
        },
        success: function(data) {
            //console.log(data);
            if (data.error) {
                window.location = "index.php?m=user&a=logout";
            } else {
                if (typeof sysCheck.get('checkOutOneMenu', 'desktop') == 'function') {
                    //处理拿过来的值
                    processPhoneStatisticsInDesktop(data.phone_today_statistics);
                }else{
					processPhoneStatisticsNotInDesktop(data.phone_today_statistics);
				}
                //给分机状态赋值
                if (_my_exten) {
                    if (data.user_status_text != '' && $('#user_status_text') != null) {
                        $('#user_status_text').html(data.user_status_text + data.tips);
                        $("#user_status_fa").attr('class', 'user_status_' + data.user_status + ' ' + data.user_status_icon);
                        $("#user_status_fa").attr('title', data.tips);

                        // 如果是通话状态刚刚建立，就把分机暂停掉
                        if (now_user_status == 1 && data.user_status == 2) {
                            var url = 'index.php?m=Api&a=queuePauseOpt&type=1&extension=' + _my_exten;
                            $.getJSON(url + '&t=' + Math.random(), function(data) {});
                        }

                        now_user_status = data.user_status;

                    }
                }
                //触发弹屏
                if (data.call_uid != "NULL" && data.call_uid != now_call_uid) {
                    now_call_uid = data.call_uid;
                    var newphone = {
                        'call_uid': data.call_uid,
                        'call_phone': data.call_phone,
                        'call_time': data.call_time,
                        'call_cid': data.call_cid,
                        'call_did': data.call_did,
                        'call_queue_id': data.call_queue_id,
                        'call_type': data.call_type,
                        'call_type_text': data.call_type_text,
                        'call_type_icon': data.call_type_icon,
                        'call_type_color': data.call_type_color
                    };
                    if (!(typeof phoneslist[0] != 'undefined' && phoneslist[0]['call_uid'] == data.call_uid)) {
                        phoneslist.unshift(newphone);
                    }
                    phoneslist.length = 10; //留下10条记录
                    var s = "";
                    for (var i = 0; i < phoneslist.length; i++) {
                        if (typeof(phoneslist[i]) != "undefined" && phoneslist[i]['call_uid'] != null) {

                            s += '<li><a id="phonelist_' + phoneslist[i]['call_uid'].replace('.', '') + '" style=" cursor:pointer;" onclick="view_Customer(' + phoneslist[i]['customer_id']+','+phoneslist[i]['queue_id']+ ')">';
                            s += '<span class="label ' + phoneslist[i]['call_type_color'] + '">';
                            s += '<i class="fa ' + phoneslist[i]['call_type_icon'] + '"></i></span>' + phoneslist[i]['call_phone'];
                            s += '<span class="pull-right text-muted small">' + phoneslist[i]['call_time'] + '</span></a></li>';
                        }
                    }

                    $("#div_phone_list").html("<ul>" + s + "</ul>");
					//console.log(typeof sysCheck.get('checkOutOneMenu', 'desktop'));
                    //只有振铃或者通话中，才弹屏		
                    if (typeof sysCheck.get('checkOutOneMenu', 'desktop') == 'function') {
                        sysCheck.get('checkOutOneMenu', 'desktop')(data);
                        
                    } else {
                        //console.log(data);
                        $.post("index.php?m=customer&a=popPage", {
                            phone_num: data.call_phone,
                            call_uid: data.call_uid,
                            call_queue_id: data.call_queue_id,
                            t: Math.random(1000)
                        }, function(result) {

							var data = eval(result);
							if(typeof data[0] != 'undefined' && data[0].customer_id > 0)
							{
                              //重新排序
                              //console.log(data);
                              if(data[0].customer_id)
                               {
                                 view_Customer(data[0].customer_id,data[0].call_queue_id);
                                }
							  $("#phonelist_"+data[0]['call_uid'].replace('.','')).attr('onclick','view_Customer('+data[0]['customer_id']+','+data[0]['queue_id']+')');
		                      phoneslist[0]['customer_id'] = data[0]['customer_id'];
							}
						});
                    }
                }

                //触发消息
                if (data.have_noc > 0) {

                    if (noc_id != data.have_noc) {
                        noc_id = data.have_noc;
                        noc_mon();
                    }
                } else {
                    nbsp = '';
                    noc_id = 0;
                    jQuery("#message_count").html(nbsp);
                }

            }

        },
        error: function(request, textStatus, errorThrown) {

        }
    });
    setTimeout(keep_online, 1000);
}

function init_form() {
    $(".form-validate").validate({
        errorPlacement: function(error, element) {
            error.insertAfter(element);
        }
    });
    $(".form-validate-signin").validate({
        errorPlacement: function(error, element) {
            error.insertAfter(element);
        }
    });
    $(".form-validate-signup").validate({
        rules: {
            age: {
                range: [0, 100]
            }
        },
        errorPlacement: function(error, element) {
            error.insertAfter(element);
        }
    });
}


function modalUrl(url) {
    //alert(url);
    url += '&t=' + Math.random(1000)
    $.get(url, '', function(data) {
        $('#mymodal').html(data);
        init_form();
    })
    $('#mymodal').modal({
        show: true
    });
}


// 展开隐藏信息面板 zhangtuo 2015-11-3
function showPanel(url) {

    //隐藏掉滚动条，并设置宽度
    $("body").eq(0).width($("body").eq(0).width());
    $("body").eq(0).css("overflow", "hidden");
    //定位面板的位置
    //alert("展开面板");

    $.get(url + '&t=' + Math.random(1000), function(data) {
        //alert("Data Loaded: " + data);
        $("#info-panel .panel-inner").html(data);
        $('#info-panel .panel-inner').slimScroll({
            height: $(window).height() - 50,
            width: '950px',
            alwaysVisible: true,
            wheelStep: 100
        });

        $('#info-panel').css('margin-top', $(document).scrollTop());
        $('#info-panel').css('right', '-950px');
        $('#info-panel').css('height', $(window).height() - 50);

        $('#info-panel').show();
        $('#info-panel').animate({
            right: '0px'
        });


    });

};


//添加任务日程
// url_param string 类型，必须项r=RCustomerTask&module=customer&id={$customer.customer_id}
function add_task(url_param) {
    $.get('index.php?m=todo&a=add&t=' + Math.random(1000), url_param, function(data) {
        parent.layer.open({
            type: 1,
            area: ['530px', '400px'],
            title: '添加任务',
            shadeClose: true,
            content: data
        });
    })
}

function edit_task(url_param) {
    $.get('index.php?m=todo&a=edit&t=' + Math.random(1000), url_param, function(data) {
        parent.layer.open({
            type: 1,
            area: ['530px', '400px'],
            title: '编辑任务',
            shadeClose: true,
            content: data
        });
    })
}


function init_InfoPanel() {
    $(".page-content").bind("click", function(e) {

        var target = $(e.target);
        //console.log(target); 
        if (target.closest(".like").length == 0) {

            $('#info-panel').animate({
                right: '-950px'
            });
            $('#info-panel').hide();

            //$('#info-panel').animate({right:'0px',width:'hide'},1000);
            $("body").eq(0).css("overflow-y", 'auto');
            $("#info-panel .panel-inner").html("");
        };



        //$('#info-panel').hide();
    });


}



//请求一个url，返回结果并显示，可以设置是否弹出确问询
function ajax_do(url, param, show_confirm, confirm_title, confirm_text) {
    if (show_confirm) {
        swal({
                title: confirm_title,
                text: confirm_text,
                type: "info",
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                showCancelButton: true,
                closeOnConfirm: false,
                showLoaderOnConfirm: true,
            },
            function() {
                $.post(url + '&t=' + Math.random(1000), param, function(data) {
                    swal.close();
                    parent.layer.open({
                        type: 1,
                        title: false,
                        closeBtn: false,
                        shadeClose: true, //点击遮罩层 关闭
                        content: data,
                        end: function(index) {

                        }
                    });

                }, 'html');

            });
    } else {
        $.post(url + '&t=' + Math.random(1000), param, function(data) {
            parent.layer.open({
                type: 1,
                title: false,
                closeBtn: false,
                shadeClose: true, //点击遮罩层 关闭
                content: data,
                end: function(index) {
                    //parent.layer.closeAll();

                }
            });

        }, 'html');

    }

}

//绘画出柱状图
function getChangeXml(val, chart_name, swf) {
    if (typeof(swf) == 'undefined') {
        swf = "column3d.swf"
    }
    var so = new FusionCharts(_public_path + "/images/charts/" + swf, "ChartId", "1000", "400");
    so.addParam("wmode", "transparent");
    so.setDataXML(val);
    so.render(chart_name);
}

var nowPageUrl = "";
var nowPageTitle = "";
var nowPageTarget = "";

function loadPage(pageTitle, url, target) {

    $('#info-panel').animate({
        right: '-950px'
    });
    $('#info-panel').hide();

    nowPageTitle = pageTitle;
    nowPageUrl = url;
    nowPageTarget = target;
    if (target == "_blank") {
        window.open(url);
    } else {
        $("#page_title").html(pageTitle);
        sysCheck.pageChange(url);
        if (target == 0 || target == "") {
            $("#nanyou-page-content").load(url + '&nanyou_hide_footer=1&nanyou_hide_header=1&t=' + Math.random(1000));
        } else {
            $("#" + target).load(url + '&nanyou_hide_footer=1&nanyou_hide_header=1&t=' + Math.random(1000));
        }
    }
}

function reloadPage() {
    loadPage(nowPageTitle, nowPageUrl, nowPageTarget);
}
//读取返回的json字符串，生成最新消息列表
function getThreeMessages() {
    //消息个数
    // var a = 2;
    // alert($('#message_count').innerText);
    // $('#message_count').innerText = a;
    var date = new Date();
    $.ajax({
        url: 'index.php?m=Message&a=getMes',
        success: function(data) {
            notesJson = eval(data);
            if (data == notesJsonCopy)
                return;

            //消息id
            $idArray = $('.message_id');
            //消息内容
            $noteArray = $('.note');
            //消息发送时间
            $smallArray = $('.small');
            // alert($message_count.innerText);
            for (var i = 0; i < data.length; i++) {
                $("#mes").append("<li><a class='message_id'><span class='label label-blue'><i class='fa fa-comment'></i></span><span class='note'></span><span class='pull-right text-muted small'></span></a></li>");
                $noteArray[i].innerText = notesJson[i]['note'];
                $smallArray[i].innerText = notesJson[i]['send_time'];
                var id = notesJson[i]['message_id'];
                $idArray[i].href = "javascript:view_message(" + id + ");"
            }

        }

    });
    notesJsonCopy = notesJson;



}

//检测坐席签入状态
//如果是未签入，返回0，即没有打开签入页面
//如果是就绪，返回1  
//如果是示忙,返回2
function checkDesktopStatus() {
    if ($('#switch-state').attr('checked')) {
        return true;
    } else {
        return false;
    }
}



function popPhoneBox(call_uid, call_phone, call_time, call_cid, call_did, call_queue_id, call_type, call_type_text, call_type_icon) {

    $.getJSON('index.php?m=customer&a=popPage&phone_num=' + call_phone + '&call_uid=' + call_uid + '&t=' + Math.random(1000), '', function(data) {
        if (data.customer_id != 0) {
            var url = 'index.php?m=customer&a=view&id=' + data.customer_id;
        } else {
            var url = 'index.php?m=customer&a=add&phone_num=' + call_phone;
        }


        layer.open({
            type: 1,
            title: false,
            closeBtn: 0, //不显示关闭按钮
            shade: [0], //透明度0 ，全透明

            area: ['340px', '215px'],
            offset: 'rb', //右下角弹出
            time: 600, //2秒后自动关闭
            shift: 1,
            content: '<div>' + call_type_text + " : " + call_phone + '</div>', //iframe的url，no代表不显示滚动条
            end: function() { //此处用于演示
                $.get(url + '&t=' + Math.random(1000), '', function(data) {
                    var h = $(window).height();
                    var w = $(window).width();
                    layer.open({
                        type: 1,
                        title: call_phone + "　　" + call_type_text + "　　来自:" + call_queue_id,
                        closeBtn: true, //不显示关闭按钮
                        shadeClose: true,
                        offset: [ //为了演示，随机坐标
                            Math.random() * (100), Math.random() * ($(window).width() - 950)
                        ],
                        shade: false,
                        scrollbar: true,
                        maxmin: true, //开启最大化最小化按钮
                        area: ['950px', (h - 100) + 'px'],
                        content: data,
                    });
                });
            }
        });



    });



}


//点击拨号方法
//phone 拨打哪个号码
//附件参数，默认为空 
//主叫名字，默认为空
//zhangtuo  2016-5-13 
function dial(phone, variable, callername,is_predial) {
	//console.log(phone);
         //	console.log(is_predial);
    var url = 'index.php?m=api&a=clickCall&phone=' + phone + '&variable=' + variable + '&callername=' + callername + '&is_predial='+is_predial+'&' + Math.random();
    console.log(url);   
 $.getJSON(url, function(data) {
        console.log(data);
        if (data.error>0) {
            swal(data.msg, " ","info");
        }
         
    });

}


//设置免打扰
//1表示开启免打扰
//0表示关闭免打扰
function setDND(is_dnd) {
    var url = 'index.php?m=api&a=setDND&is_dnd=' + is_dnd + '&' + Math.random();
    $.getJSON(url, function(data) {
        if (data.error > 0) {
            swal(data.msg, "", "warning");
        }
    });
}
/**
 * 处理今日通话，更新到坐席签入页面，引出下一个操作，如果全部电话有变化,并且当前处在坐席签入页面
 * @param  $sec int 秒
 * 2016-11-09
 * dongjun
 */
function processPhoneStatisticsInDesktop(statistics) {
    if (!statistics) {
        return this;
    }
    var c_1 = statistics.c_1; //话务量
    var c_5 = statistics.c_5; //漏接量
    var c_2 = statistics.c_2; //接通量
    var c_3 = statistics.c_3; //通话时长
    var c_4 = 0;
    c_5 = !c_5 ? 0 : c_5;
    c_4 = c_2 == 0 ? 0 : sec_format(c_3 / c_2);
    c_3 = sec_format(c_3);
    $("#phone_statistics_c_1_f,#phone_statistics_c_1_s").text(c_1);
    $("#phone_statistics_c_2").text(c_2);
    $("#phone_statistics_c_3").text(c_3);
    $("#phone_statistics_c_4").text(c_4);
    $("#phone_statistics_c_5").text(c_5);
    if (dayPhoneCount < c_1 && typeof updateCdrBox == 'function') {
        updateCdrBox(c_1 - dayPhoneCount);
        dayPhoneCount = c_1;
    }

}
/**
 * 处理今日通话，更新到坐席签入页面，引出下一个操作，如果全部电话有变化,并且当前不在坐席签入页面
 * @param  $sec int 秒
 * 2016-11-09
 * dongjun
 */
function processPhoneStatisticsNotInDesktop(statistics)
{
   if (!statistics) {
        return this;
   }	
   var c_1 = statistics.c_1; //话务量
  if (dayPhoneCount < c_1)
  {
	var c = c_1 - dayPhoneCount;
	$.getJSON('index.php?m=cdr&a=getCustomerDataByLimit&limit='+c+'&t='+Math.random(1000), '', function(data){
		 for(var x in data)
		 {	
		   if(data[x].call_status == 334)
		   {
			 //更新顶部栏最近10通电话的状态
			 $("#phonelist_"+data[x].uniqueid).children('span').eq(0).addClass('label-danger').removeClass('label-success'); 
			 if(phoneslist[x].call_uid.replace('.','') == data[x].uniqueid)
			 {
			   phoneslist[x].call_type_color = 'label-danger';
			 }
		   }
		 }
	});
	dayPhoneCount = c_1;
  }
}

/**
 * 格式化秒
 * @param  $sec int 秒
 * 2016-11-09
 * dongjun
 */
function sec_format($sec) {
    var $sec = parseInt($sec);
    if ($sec) {
        var $min = Math.floor($sec / 60);
        if ($min >= 60) {
            return toDecimal($min / 60, 2) + ":" + toDecimal($min % 60, 2) + ":" + toDecimal($sec % 60, 2);
        } else {
            return toDecimal($min, 2) + ":" + toDecimal($sec % 60, 2);
        }
    } else {
        return "00:00";
    }
}
/**
 * 强制取整，并且固定位数，不足的前面补0
 * @param  $num int 只接受整数
 * 2016-11-09
 * dongjun
 */
function toDecimal(num, n) {
    var num = parseInt(num);
    if (isNaN(num)) {
        return false;
    }
    var num_str = num.toString();
    var len = num_str.length;
    if (len < n) {
        while (num_str.length < n) {
            num_str = "0" + num_str;
        }
    }
    return num_str;
}
/**
 * 查看某个客户资料
 * @param  $id int 客户的ID
 * 2016-12-05
 * dongjun
 */
function view_Customer(id,queue_id,guoqi){
    if (guoqi==1) {
      layer.msg('该客户已经过期，请点击其他有效客户！',{icon: 5});
      return false  
    }
    
   $.getJSON(_root_path+'/index.php?m=customer&a=checkCustomerSeaUser&customer_id='+id+'&queue_id='+queue_id,function(data){
	    if(data['status'] == true){
          showPanel(_root_path+'/index.php?m=customer&a=view&id='+id+'&queue_id='+queue_id);
		}else{
		  layer.msg(data.msg,{icon: data.icon});
		}
   });
}
/*console.log(cookie('color'));*/
